﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Timers;
using Autofac;
using System.Reflection;
using Core;
using System.ServiceModel;
using System.Net;
using Alos.Service;

namespace Alos
{
    partial class AlosService : ServiceBase
    {
        public const string Name = "Alos";
        public const string Description = "云课堂服务";

        public static Timer SecondTimer = new Timer(1000), MinuTimer = new Timer(1000);
        public static WebClient wc = new WebClient();
        public static DateTime nowTime = DateTime.Now;
        public static List<KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>>> SyncTime = new List<KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>>>();


        public AlosService()
        {
            InitializeComponent();
            wc.Encoding = System.Text.Encoding.GetEncoding("utf-8");
            var sns = ConfigHelper.GetConfigString("SyncTime").Split(';');
            foreach (var ns in sns)
            {
                var _sns = ns.Replace("-", ":").Split(':');
                SyncTime.Add(new KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>>(new KeyValuePair<int, int>(Convert.ToInt32(_sns[0]), Convert.ToInt32(_sns[1])), new KeyValuePair<int, int>(Convert.ToInt32(_sns[2]), Convert.ToInt32(_sns[3]))));
            }
        }

        protected override void OnStart(string[] args)
        {
            #region 启动定时器
            try
            {
                SecondTimer.Elapsed += new ElapsedEventHandler(Second_Elapsed);
                SecondTimer.AutoReset = true;
                SecondTimer.Interval = ConfigHelper.GetConfigInt("Interval") * 1000;
                SecondTimer.Start();
                MinuTimer.Elapsed += new ElapsedEventHandler(Minu_Elapsed);
                MinuTimer.AutoReset = true;
                MinuTimer.Interval = ConfigHelper.GetConfigInt("MinuInterval") * 1000 * 60;
                MinuTimer.Start();
            }
            catch (Exception ex)
            {
                Log.errorlog(ex);
            }
            #endregion

            #region 启动WCF
            ServiceHost host = new ServiceHost(typeof(Operation));
            host.Open();
            #endregion

            Log.errorlog(new Exception("服务启动成功！"));
        }

        protected override void OnStop()
        {
            SecondTimer.Stop();
            Log.errorlog(new Exception("服务已停止！"));
        }

        private void Second_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            #region 指定时间段下载备课
            if (InSyncTime())
            {
                Core.FunHelper.TryAsync(() =>
                {
                    if (ConfigHelper.GetConfigInt("LessionAsyncType") == 0)//校园网部署时，以教室编号的方式进行下载备课
                    {
                        var RoomIds = ConfigHelper.GetConfigString("RoomID").Split(',');
                        if (RoomIds.Length > 0)
                        {
                            int _rid = 0;
                            foreach (var rid in RoomIds)
                            {
                                if (int.TryParse(rid, out _rid) && _rid > 0)
                                    new DAL.ReLessionDAL().DownLession(Convert.ToInt32(rid));
                            }
                        }
                    }
                    else if (ConfigHelper.GetConfigInt("LessionAsyncType") == 2) //互联网部署时，以学校编号的方式下载备课
                    {
                        new DAL.ReLessionDAL().DownLession(0, 2);
                    }
                    new DAL.GroupInfoDAL().GetGroupInfo();
                    new DAL.GroupInfoDAL().DelGroupInfo();
                    return true;
                });
            }
            #endregion

            #region 上传课件批注至服务器
            Core.FunHelper.TryAsync(() =>
            {
                new DAL.PreparingNotationUpLoad().Up();
                new DAL.PreparingNotationUpLoad().UpRes();
                return true;
            });
            #endregion

            #region 重新下载未完成资源
            Core.FunHelper.Try(() => {
                new DAL.ReResource().ReDownNotComplatedResource();
            });
            #endregion
        }

        private void Minu_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            #region 用户行为提交云端
            if (InSyncTime())
            {

                Core.FunHelper.Try(DAL.ReResourceRecordDAL.AsyncData);
                Core.FunHelper.Try(DAL.ReResourceEvaluateRecordDAL.AsyncData);
                Core.FunHelper.Try(DAL.ReTeacherRecordDAL.AsyncData);
                Core.FunHelper.Try(DAL.ReStudentClassRecordDAL.AsyncData);
                Core.FunHelper.Try(DAL.ReClassSignDAL.AsyncData);
                Core.FunHelper.Try(DAL.ReDiscussDAL.AsyncData);
                Core.FunHelper.Try(DAL.ReActivityDetailDAL.AsyncData);
                Core.FunHelper.Try(DAL.ReActivityDAL.AsyncData);
                Core.FunHelper.Try(DAL.ReWhiteBroadDetailDAL.AsyncData);
                Core.FunHelper.Try(DAL.ReWhiteBroadDAL.AsyncData);
                Core.FunHelper.Try(DAL.ReExamDetailDAL.AsyncData);
                Core.FunHelper.Try(DAL.ReExamSubmitDAL.AsyncData);
                Core.FunHelper.Try(DAL.ReExamSubjectDAL.AsyncData);
                Core.FunHelper.Try(DAL.ReExamDAL.AsyncData);
                Core.FunHelper.Try(DAL.ReVoteDetailDAL.AsyncData);
                Core.FunHelper.Try(DAL.ReVoteDAL.AsyncData);
                Core.FunHelper.Try(DAL.RePutQuestionDetailDAL.AsyncData);
                Core.FunHelper.Try(DAL.RePutQuestionDAL.AsyncData);
                Core.FunHelper.Try(DAL.ReFeedbackDetailDAL.AsyncData);
                Core.FunHelper.Try(DAL.ReFeedbackBatchDAL.AsyncData);
                Core.FunHelper.Try(DAL.ResorceInvateDAL.AsyncData);
                Core.FunHelper.Try(DAL.ReArrangeRecordDAL.AsyncData);
                Core.FunHelper.Try(DAL.ReSubmitRecordDAL.AsyncData);
                Core.FunHelper.Try(DAL.ReObjectiveQuestionDAL.AsyncData);
                Core.FunHelper.Try(DAL.ReSubjectiveQuestionDAL.AsyncData);
                Core.FunHelper.Try(DAL.StudentNoteProblemDAL.AsyncData);
                Core.FunHelper.Try(DAL.StudentNoteProblemCommentDAL.AsyncData);
            }
            #endregion
        }

        private bool InSyncTime()
        {
            var now = DateTime.Now;
            bool inSt = false;
            SyncTime.ForEach(item =>
            {
                if (!inSt)
                    inSt = (now.Hour > item.Key.Key || now.Hour == item.Key.Key && now.Minute >= item.Key.Value) && (now.Hour < item.Value.Key || now.Hour == item.Value.Key && now.Minute <= item.Value.Value);
                else
                    return;
            });
            return inSt;
        }
    }
}
